package com.feifan.web.controller.oa;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.feifan.common.annotation.Log;
import com.feifan.common.core.controller.BaseController;
import com.feifan.common.core.page.TableDataInfo;
import com.feifan.common.enums.BusinessType;
import com.feifan.common.utils.baiduai.BaiDuAiResult;
import com.feifan.common.utils.baiduai.FaceUtils;
import com.feifan.common.utils.baiduai.GroupUtils;
import com.feifan.framework.util.ShiroUtils;
import com.feifan.oa.domain.Attendance;
import com.feifan.oa.domain.Face;
import com.feifan.oa.service.IAttendanceService;
import com.feifan.oa.service.IFaceService;
import com.feifan.system.service.ISysConfigService;
import com.feifan.web.controller.utils.Base64Util;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.List;

/**
 * 员工考勤Controller
 *
 * @author 非凡
 * @date 2020-09-19
 */
@Controller
@RequestMapping("/oa/attendance")
public class AttendanceController extends BaseController {

    private String prefix = "oa/attendance";

    @Autowired
    private IAttendanceService attendanceService;

    @Autowired
    private IFaceService faceService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 判断签到时间
     */
    public boolean isLessTime(Integer type) {
        //获取当前时间
        Calendar calendar = Calendar.getInstance();
        int clockInHour = calendar.get(Calendar.HOUR_OF_DAY);
        int clockInMin = calendar.get(Calendar.MINUTE);

        //数据库获取上下班时间
        String commuting = configService.selectConfigByKey("sys.Commuting");
        String[] commutings = commuting.split(",");


        /**
         * 上班时间判断
         * 签到时间如果 小于 上班时间 结果：上班
         * 签到时间如果 大于 上班时间 结果：上班迟到
         * 签到时间如果 等于 上班时间 -> 签到的分钟如果 大于 上班时间 结果：上班迟到
         *
         * 下班时间判断
         * 签退时间如果 小于 下班时间 结果：下班早退
         * 签退时间如果 大于 下班时间 结果：下班
         * 签退时间如果 等于 下班时间 -> 签退的分钟如果 小于 下班时间 结果：下班早退
         */
        if (type == 0) {
            //上班时间
            String[] singIn = commutings[0].split(":");
            int singInWorkHour = Integer.parseInt(singIn[0]);
            int singInWorkMin = Integer.parseInt(singIn[1]);

            //判断上班是否迟到
            if (clockInHour < singInWorkHour) {
                return true;
            }else if (clockInHour > singInWorkHour){
                return false;
            } else if (clockInHour == singInWorkHour) {
                if (clockInMin > singInWorkMin) {
                    return false;
                }
            }
        } else {
            //下班时间
            String[] singOut = commutings[1].split(":");
            int singOutWorkHour = Integer.parseInt(singOut[0]);
            int singOutWorkMin = Integer.parseInt(singOut[1]);
            //判断下班是否早退
            if (clockInHour > singOutWorkHour) {
                return true;
            } else if (clockInHour < singOutWorkHour) {
                return false;
            } else if (clockInHour == singOutWorkHour) {
                if (clockInMin < singOutWorkMin) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 签到
     *
     * @return
     */
    @RequiresPermissions("oa:attendance:view")
    @GetMapping("/signIn")
    public String signIn() {
        return prefix + "/signIn";
    }

    /**
     * 签到记录
     *
     * @return
     */
    @RequiresPermissions("oa:attendance:view")
    @GetMapping("/signInRecord")
    public String signInRecord() {
        return prefix + "/signInRecord";
    }

    /**
     * 查询员工签到列表
     */
    @RequiresPermissions("oa:attendance:list")
    @PostMapping("/signInList")
    @ResponseBody
    public TableDataInfo signInList(Attendance attendance) {
        attendance.setSysUser(ShiroUtils.getSysUser());
        attendance.setType(0);
        startPage();
        List<Attendance> list = attendanceService.selectAttendanceList(attendance);
        return getDataTable(list);
    }

    /**
     * 保存签到
     */
    @RequiresPermissions("oa:attendance:add")
    @Log(title = "员工签到", businessType = BusinessType.INSERT)
    @PostMapping("/signInAdd")
    @ResponseBody
    public BaiDuAiResult signInAdd(@RequestParam("file") String file) {
        byte[] decode = Base64.decode(Base64Util.base64Process(file));

        //查询用户是否存在人脸
        Face face = faceService.selectFaceByUID(ShiroUtils.getUserId());
        if (StringUtils.isEmpty(face)) {
            return BaiDuAiResult.warn(BaiDuAiResult.Type.NOTREGISTER, "未注册人脸");
        }

        Attendance attendance1 = attendanceService.selectAttendanceByTime(ShiroUtils.getUserId(), 0);
        if (!StringUtils.isEmpty(attendance1)) {
            return BaiDuAiResult.warn("今日已签退");
        }

        //人脸搜索
        String result = FaceUtils.search(Base64Util.encode(decode), ShiroUtils.getUserId().toString(),
                ShiroUtils.getSysUser().getDeptId().toString());

        //判断传回的值是否是json字符串
        if (com.feifan.common.utils.StringUtils.isJson(result)) {
            JSONObject res = JSON.parseObject(result);

            if (res.getInteger("error_code") == 0) {
                Attendance attendance = new Attendance();
                attendance.setSysUser(ShiroUtils.getSysUser());
                attendance.setType(isLessTime(0) ? 0:2);
                attendanceService.insertAttendance(attendance);
                return BaiDuAiResult.success("签到成功");
            }
        }
        return BaiDuAiResult.warn(result);
    }

    /**
     * 签退
     *
     * @return
     */
    @RequiresPermissions("oa:attendance:view")
    @GetMapping("/signOut")
    public String signOut() {
        return prefix + "/signOut";
    }

    /**
     * 签退记录
     *
     * @return
     */
    @RequiresPermissions("oa:attendance:view")
    @GetMapping("/signOutRecord")
    public String signOutRecord() {
        return prefix + "/signOutRecord";
    }

    /**
     * 查询员工签退列表
     */
    @RequiresPermissions("oa:attendance:list")
    @PostMapping("/signOutList")
    @ResponseBody
    public TableDataInfo signOutList(Attendance attendance) {
        attendance.setSysUser(ShiroUtils.getSysUser());
        attendance.setType(1);
        startPage();
        List<Attendance> list = attendanceService.selectAttendanceList(attendance);
        return getDataTable(list);
    }


    /**
     * 保存签退
     */
    @RequiresPermissions("oa:attendance:add")
    @Log(title = "员工签退", businessType = BusinessType.INSERT)
    @PostMapping("/signOutAdd")
    @ResponseBody
    public BaiDuAiResult signOutAdd(@RequestParam("file") String file) {
        byte[] decode = Base64.decode(Base64Util.base64Process(file));

        //查询用户是否存在人脸
        Face face = faceService.selectFaceByUID(ShiroUtils.getUserId());
        if (StringUtils.isEmpty(face)) {
            return BaiDuAiResult.warn(BaiDuAiResult.Type.NOTREGISTER, "未注册人脸");
        }

        Attendance attendance1 = attendanceService.selectAttendanceByTime(ShiroUtils.getUserId(), 1);
        if (!StringUtils.isEmpty(attendance1)) {
            return BaiDuAiResult.warn("今日已签退");
        }


        //人脸搜索
        String result = FaceUtils.search(Base64Util.encode(decode), ShiroUtils.getUserId().toString(),
                ShiroUtils.getSysUser().getDeptId().toString());

        //判断传回的值是否是json字符串
        if (com.feifan.common.utils.StringUtils.isJson(result)) {
            JSONObject res = JSON.parseObject(result);

            if (res.getInteger("error_code") == 0) {
                Attendance attendance = new Attendance();
                attendance.setSysUser(ShiroUtils.getSysUser());
                attendance.setType(isLessTime(1) ? 1:3);
                attendanceService.insertAttendance(attendance);
                return BaiDuAiResult.success("签退成功");
            }
        }
        return BaiDuAiResult.warn(result);
    }

    /**
     * 注册人脸页面
     */
    @RequiresPermissions("oa:attendance:view")
    @GetMapping("/faceRegister")
    public String faceRegister() {
        return prefix + "/faceRegister";
    }

    /**
     * 注册人脸
     */
    @RequiresPermissions("oa:attendance:add")
    @Log(title = "员工人脸注册", businessType = BusinessType.INSERT)
    @PostMapping("/faceRegister")
    @ResponseBody
    public BaiDuAiResult faceRegister(@RequestParam("file") String file) {
        byte[] decode = Base64.decode(Base64Util.base64Process(file));

        //查询用户是否存在人脸
        Face face = faceService.selectFaceById(ShiroUtils.getUserId());
        if (StringUtils.isEmpty(face)) {
            //添加用户组
            GroupUtils.addGroup(ShiroUtils.getSysUser().getDeptId().toString());
            //添加人脸
            String result = FaceUtils.addUser(Base64Util.encode(decode),
                    ShiroUtils.getSysUser().getDeptId().toString(),
                    ShiroUtils.getUserId().toString(),
                    ShiroUtils.getSysUser().getUserName());

            //判断传回的值是否是json字符串
            if (com.feifan.common.utils.StringUtils.isJson(result)) {
                JSONObject res = JSON.parseObject(result);

                if (res.getInteger("error_code") == 0) {
                    JSONObject result1 = (JSONObject) res.get("result");
                    String faceToken = result1.getString("face_token");

                    //添加数据库人脸
                    Face face1 = new Face();
                    face1.setsysUser(ShiroUtils.getSysUser());
                    face1.setFaceToken(faceToken);
                    face1.setGroupId(ShiroUtils.getSysUser().getDeptId().toString());
                    faceService.insertFace(face1);
                    return BaiDuAiResult.success("注册成功");
                }
            }
            return BaiDuAiResult.warn(result);
        } else {
            return BaiDuAiResult.warn("你已注册人脸,无需重复注册!");
        }
    }

}
